import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { User, UserSettings } from '../types/user'
import SecureLS from 'secure-ls'

// 使用 secure-ls 安全存储敏感信息
const secureStorage = new SecureLS({ encodingType: 'aes' })

export const useUserStore = defineStore('user', () => {
  // 状态
  const currentUser = ref<User | null>(null)
  const userSettings = ref<UserSettings | null>(null)
  const token = ref<string | null>(null)
  const isLoading = ref(false)
  
  // 计算属性
  const isLoggedIn = computed(() => !!currentUser.value && !!token.value)
  const isCreator = computed(() => currentUser.value?.roles.includes('creator') || currentUser.value?.roles.includes('admin') || false)
  const isAdmin = computed(() => currentUser.value?.roles.includes('admin') || false)
  
  // 动作
  function setUser(user: User | null) {
    currentUser.value = user
    if (user) {
      secureStorage.set('user', user)
    } else {
      secureStorage.remove('user')
    }
  }
  
  function setToken(newToken: string | null) {
    token.value = newToken
    if (newToken) {
      secureStorage.set('auth_token', newToken)
    } else {
      secureStorage.remove('auth_token')
    }
  }
  
  function loadUserFromStorage() {
    try {
      const storedUser = secureStorage.get('user')
      const storedToken = secureStorage.get('auth_token')
      
      if (storedUser) {
        currentUser.value = storedUser
      }
      
      if (storedToken) {
        token.value = storedToken
      }
    } catch (e) {
      console.error('Failed to load user data from secure storage', e)
      // 如果解密失败，清除数据
      secureStorage.remove('user')
      secureStorage.remove('auth_token')
    }
  }
  
  function logout() {
    currentUser.value = null
    userSettings.value = null
    token.value = null
    secureStorage.remove('user')
    secureStorage.remove('auth_token')
  }
  
  // 初始化
  loadUserFromStorage()
  
  return {
    currentUser,
    userSettings,
    token,
    isLoading,
    isLoggedIn,
    isCreator,
    isAdmin,
    setUser,
    setToken,
    loadUserFromStorage,
    logout
  }
}) 